package com.trex.modules.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JsonSenderUtil {

    /**
     * 使用 HttpURLConnection 发送 JSON 数据
     *
     * @param ip     目标 IP 地址
     * @param port   目标端口
     * @param path   目标路径
     * @param json   发送的 JSON 数据
     * @return 响应结果
     */
    public static String sendJsonWithHttpURLConnection(String ip, int port, String path, String json) {
        try {
            // 设置目标 URL 和端口
            URL url = new URL("http://" + ip + ":" + port + path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法为 POST
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setDoOutput(true);

            // 发送请求数据
            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = json.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 检查响应代码
            int responseCode = conn.getResponseCode();
            return "Response Code: " + responseCode;

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    /**
     * 使用 Apache HttpClient 发送 JSON 数据
     *
     * @param ip     目标 IP 地址
     * @param port   目标端口
     * @param path   目标路径
     * @param json   发送的 JSON 数据
     * @return 响应结果
     */
    public static String sendJsonWithHttpClient(String ip, int port, String path, String json) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 设置目标 URL 和端口
            HttpPost post = new HttpPost("http://" + ip + ":" + port + path);
            post.setHeader("Content-Type", "application/json");

            // 设置请求体
            StringEntity entity = new StringEntity(json, "UTF-8");
            post.setEntity(entity);

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                return EntityUtils.toString(response.getEntity());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}
